import axios from 'axios'
import { Toast } from 'vant'
import {getToken, removeToken} from './/auth'
let loading = null
let TIME_OUT = 20 * 1000
// 创建一个axios实例
const instance = axios.create({
    baseURL: import.meta.env.BASE_URL,
    timeout: TIME_OUT
})

// request
instance.interceptors.request.use(
    (req) => {
        // token setting
        const token = getToken()
        if(token){
            req.headers['Authorization'] = token
        }
        if (typeof req.loading === 'undefined' ? false : req.loading) {
            loading = Toast.loading({
                message: '加载中',
                forbidClick: true,
                loadingType: 'spinner',
                duration: TIME_OUT
            })
        }
        return req
    },
    (err) => {
        Promise.reject(err)
    }
)

// 拦截返回的数据
instance.interceptors.response.use(response => {
    // 状态码为200的会进入到这里
    if (loading) {
        loading.clear()
    }
    const {msg, code} = response.data
    if (code == '0') {
        return response.data
    }else {
        Toast({
            type: 'fail',
            message: msg,
            duration: 2.5 * 1000
        })
        return Promise.reject(msg)
    }
}, error => {
    // 除状态码200以外的错误会进入到这里
    Toast({
        type: 'fail',
        message: error.message,
        duration: 2.5 * 1000
    })
    if(error.response.status === 401 && import.meta.env.DEV){ // 未授权且开发模式下
        removeToken()
        location.reload()
    }
    return Promise.reject(error)
})

export default instance
